#include "include/spi.h"
#include "stdio.h"
#include "string.h"
#include "driver/spi_common.h"
#include "driver/gpio.h"
#include "driver/spi_master.h"




/*SPI2总线句柄*/
spi_device_handle_t SPI2_handle;
/*默认的SPI2的传输速度为10khz*/
unsigned int spi2_speed = 10 * 1000;
/*初始化与SD卡相连的SPI2端口*/
void SPI2_Init(void)
{
    /*配置SPI2主机*/
    spi_bus_config_t bus_config = {0};
    bus_config.miso_io_num = MISO_PIN;
    bus_config.mosi_io_num = MOSI_PIN;
    bus_config.sclk_io_num = SCLK_PIN;
    bus_config.quadhd_io_num = -1;
    bus_config.quadwp_io_num = -1;
    bus_config.max_transfer_sz = 40000;      /*最大传输字节数*/

    // 初始化总线（HOST_ID 必须为 SPI2_HOST，确保
    ESP_ERROR_CHECK(spi_bus_initialize(HOST_ID, &bus_config, SPI_DMA_CH_AUTO));


    /*添加SD卡总线到SPI2*/
    spi_device_interface_config_t sd_config = {0};
    sd_config.mode = 0;                      /*SPI模式0*/
    sd_config.spics_io_num = CS_PIN;
    sd_config.clock_speed_hz = 20 * 1000;    /*spi速率1Mhz*/
    sd_config.queue_size = 7;                /*事务队列尺寸7个*/
    ESP_ERROR_CHECK(spi_bus_add_device(SPI2_HOST, &sd_config, &SPI2_handle));

}

/**
 * 功能：发送与接收8位数据的SPI2数据
 * 参数：tx_data:需要发送的8位数据
 * 返回值：返回接收到的8位数据 
 * */
unsigned char SPI2_Send_Recv_8bit_Data(unsigned char tx_data)
{
    /*打包数据并发送*/
    unsigned char rx_data;
    spi_transaction_t trans_desc;
    trans_desc.flags = 0;  /*普通SPI模式*/
    trans_desc.length = 8;  /*发送数据长度*/
    trans_desc.rxlength = 8;    /*接收数据长度*/
    trans_desc.override_freq_hz = spi2_speed;
    trans_desc.rx_buffer = &rx_data;
    trans_desc.tx_buffer = &tx_data;
    ESP_ERROR_CHECK(spi_device_polling_transmit(SPI2_handle, &trans_desc));
    return rx_data;
}

/**
 * 功能：发送与接收n位数据的SPI2数据
 * 参数：tx_data:需要发送的8位数据地址
 *       rx_data:需要接收的8位数据地址
 *       n:字节数
 * 返回值：空
 * */
void SPI2_Send_Recv_n_bit_Data(void* tx_data, void *rx_data, int n)
{
    printf("n的值: %d\r\n", n);
    if(tx_data == NULL)
    {
        tx_data = malloc(n);
        memset(tx_data, 0xFF, n);
    }
    
    /*打包数据并发送*/
    spi_transaction_t trans_desc;
    trans_desc.flags = 0;  /*普通SPI模式*/
    trans_desc.length = n * 8;  /*发送数据长度*/
    trans_desc.rxlength = trans_desc.length;    /*全双工下，接收与发送的数据长度一致*/
    trans_desc.override_freq_hz = spi2_speed;
    trans_desc.rx_buffer = rx_data;
    trans_desc.tx_buffer = tx_data;
    ESP_ERROR_CHECK(spi_device_polling_transmit(SPI2_handle, &trans_desc));
    free(tx_data);
    return ;
}


/*配置SPI2速度的函数*/
void SPI2_Set_speed(unsigned int speed)
{
    spi2_speed = speed;
}